package com.heima.search.service.impl;

import com.heima.common.Threadlocals.UserThreadLocalUtil;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.search.dto.ApArticleSearchDto;
import com.heima.search.entity.ApUserSearch;
import com.heima.search.repository.ApUserSearchRepository;
import com.heima.search.service.IApUserSearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author: itheima
 * @create: 2022-07-12 14:55
 */
@Service
public class ApUserSearchServiceImpl implements IApUserSearchService {


    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private ApUserSearchRepository userSearchRepository;


    /**
     * 保存搜索历史到MongoDB中
     *
     * @param keyword     关键字
     * @param userId      用户ID
     * @param equipmentId 设备ID
     */
    @Override
    @Async("leadnewsExecutor")
    public void saveSearchRecord(String keyword, Integer userId, String equipmentId) {
        //1.判断关键字用户是否已经搜索过
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId));
        query.addCriteria(Criteria.where("keyword").is(keyword));
        long count = mongoTemplate.count(query, ApUserSearch.class);

        //2.搜过更新时间即可
        if (count > 0) {
            Update update = new Update();
            update.set("createdTime", new Date());
            mongoTemplate.updateFirst(query, update, "apUserSearch");
            return;
        }
        //3.没搜过新增
        ApUserSearch apUserSearch = new ApUserSearch();
        apUserSearch.setKeyword(keyword);
        apUserSearch.setUserId(userId);
        apUserSearch.setEquipmentId(equipmentId);
        apUserSearch.setCreatedTime(new Date());
        mongoTemplate.save(apUserSearch);
    }

    /**
     * 根据用户ID查询用户搜索历史
     *
     * @param dto 查询条件
     * @return
     */
    @Override
    public ResponseResult load(ApArticleSearchDto dto) {
        User user = UserThreadLocalUtil.get();
        List<ApUserSearch> list = userSearchRepository.findTop5ByUserIdOrderByCreatedTime(user.getUserId());
        return ResponseResult.okResult(list);
    }

    /**
     * 批量删除 搜索历史
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult delete(ApArticleSearchDto dto) {
        userSearchRepository.deleteAll(dto.getHisList());
        return ResponseResult.okResult();
    }
}
